/*
创建web服务器，设置端口8080，添加事件，根据请求作出响应
'/list'   响应  '这是商品列表'
'/index'    响应文件'1.html'，先读取文件，然后把读取的内容作为响应的内容
'/study'   跳转到 https://www.baidu.com
其它    响应状态码404    not found
*/

const http = require("http");
const fs = require("fs");

const app = http
    .createServer((req, res) => {
        console.log(`${req.method}\t${req.url}\t${res.statusCode}`);
    })
    .listen(8080);

app.on("request", (req, res) => {
    let url = req.url.split("?")[0];

    if (url == "/list") {
        res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
        res.write("这是商品列表");
    } else if (url == "/index" || url == "/") {
        let html = fs.readFileSync("./nodejs/03-同步异步读写、http/1.html");
        res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
        res.write(html.toString());
    } else if (url == "/study") {
        res.writeHead(302, { Location: "https://www.baidu.com" });
    } else {
        res.writeHead(404, { "Content-Type": "text/html;charset=utf-8" });
        res.write("not found");
    }

    res.end();
});
